<?php
namespace app\common\service;

use think\Model;
use app\common\model\Track as Track;

class TrackService extends Model
{
    /**
     * 获得粉丝动态
     * 粉丝就是没有填写资料的人
     * @param $uid 顾问的ID
     */
    public function getTrackListFansByUID($uid, $p, $size = 10)
    {
        //$track = model('Track');
        $start_row = ($p - 1) * $size;
        $end_row = $start_row + $size;


        /*
        Db::table('think_artist')
            ->alias('a')
            ->join('think_work w','a.id = w.artist_id')

        */

        /*
        \think\Db::listen(function($sql, $time, $explain){
            // 记录SQL
            echo $sql. ' ['.$time.'s]';
            // 查看性能分析结果
            dump($explain);
        });
        */

        // 使用闭包查询
        $track = Track::select(function ($query) use ($uid, $start_row, $end_row, $size) {
            $query->alias('a')
                ->join('students s', 'a.uid = s.uid', 'LEFT')
                ->join('user u', 'a.uid = u.user_id', 'LEFT')
                ->where('a.counselor_id', $uid)
                ->where('s.company', null)
                ->order('track_id DESC')
                ->limit($start_row, $size);
        });
        \think\Db::execute("UPDATE dms_track AS a LEFT JOIN dms_students s ON a.uid = s.uid SET isRead='1' WHERE a.counselor_id =$uid and s.company is NULL ");
        return $this->getTrackListFormat($track);
    }


    /**
     * 获得客户动态
     * @param $uid 顾问的ID
     */
    public function getTrackListCustomerByUID($uid, $p, $size = 10)
    {
        //$track = model('Track');
        $start_row = ($p - 1) * $size;
        $end_row = $start_row + $size;
        $field = 'a.track_id,a.pubdate,a.a,a.msg,u.user_id,u.user_headimgurl,u.user_name,u.user_nickname,s.id as student_id';

        // 使用闭包查询
        $track = Track::select(function ($query) use ($uid, $start_row, $end_row) {
            $field = 'a.track_id,a.pubdate,a.a,a.msg,u.user_id,u.user_headimgurl,u.user_name,u.user_nickname,s.id as student_id';
            $group = 'a.track_id,a.pubdate,a.a,a.msg,u.user_id,u.user_headimgurl,u.user_name,u.user_nickname,s.id';
            $query->alias('a')
                ->join('students s', 'a.uid = s.uid', 'LEFT')
                ->join('user u', 'a.uid = u.user_id', 'LEFT')
                ->join('user_integral ui', 'a.uid = ui.userid', 'LEFT')
                ->field($field)
                ->where([
                    'a.counselor_id' => $uid,
                    //'s.company' => ['neq', ''],
                    'a.uid' => ['neq', $uid],
                    'ui.counselor_status' => 0
                ])
                ->order('track_id DESC')
                ->group($group)
                ->limit($start_row, $end_row);
        });


        \think\Db::execute("UPDATE dms_track AS a LEFT JOIN dms_students s ON a.uid = s.uid SET isRead='1' WHERE a.counselor_id =$uid and s.company !=''");

        return $this->getTrackListFormat($track);
    }


    /**
     * 获得客户动态
     * @param $cid 客户的ID,如果是0就是这个顾问的所有客户的动态
     */
    public function getTrackListByCID($cid, $p, $size = 10)
    {
        //$track = model('Track');

        $start_row = ($p - 1) * $size;
        $end_row = $start_row + $size;
        // 使用闭包查询
        $track = Track::select(function ($query) use ($cid, $start_row, $end_row) {
            $query->alias('a')
                ->join('user u', 'a.uid = u.user_id', 'LEFT')
                ->where('uid', $cid)
                ->order('track_id DESC')
                ->limit($start_row, $end_row);
        });
        //总条数
        $list_count = db('track')->alias('a')
            ->join('user u', 'a.uid = u.user_id', 'LEFT')
            ->where(['a.uid' => $cid])
            ->count();
        $list = $this->getTrackListFormat($track);
        return ['content' => $list, 'page' => ['count' => $list_count]];
    }

    /**
     * 获得客户动态
     * @param $cid 客户的ID,如果是0就是这个顾问的所有客户的动态
     */
    public function getTrackCountByUID($uid)
    {

//         $data['count'] = Track::where(['pid' => $uid])->column('count(*)');
        $where = [
            't.isRead' => 0,
            't.counselor_id' => $uid,
            'ui.counselor_status' => 0,
            'ui.students_id' => ['>', 0],
            's.company' => ['neq', '']
        ];
        $data['count'] = db('track')
            ->alias('t')
            ->join('user_integral ui', 'ui.userid = t.uid', 'LEFT')
            ->join('students s', 't.uid = s.uid', 'LEFT')
            ->where($where)
            ->count();
        return $data;
    }

    /**
     * 获取用户某客户的最新动态
     * @param int $sid 店铺ID
     * @param int $uid 用户ID
     * @param int $cid 客户ID
     * @return array()
     */
    public function getOneRecentTrackByCID($sid, $uid, $cid)
    {
        $recent_track = Track::where(['sid' => $sid, 'uid' => $cid, 'counselor_id' => $uid])->order('track_id DESC')->find();
        return $recent_track;
    }

    /**
     * 获取某客户的最新动态
     * @param int $sid 店铺ID
     * @param int $uid 用户ID
     * @param int $cid 客户ID
     * @return array()
     */
    public function getOneRecentTrackByOnlyCID($sid, $cid)
    {
        $recent_track = Track::where(['sid' => $sid, 'uid' => $cid])->order('track_id DESC')->find();
        return $recent_track;
    }

    /**
     * 格式化动态数据
     * @param $track
     * @return mixed
     */
    private function getTrackListFormat($track)
    {
        $result = array_reduce($track, function ($result, $v) {
            $item['cid'] = $v->user_id;
            $item['pubdate'] = $v->pubdate;

            if ('topic_detail' == $v->a) {
                $item['msg'] = '阅读了:' . $v->msg;
            } else {
                $item['msg'] = $v->msg;
            }

            $item['user_nickname'] = $v->user_nickname;
            $item['user_name'] = $v->user_name;
            $item['user_headimgurl'] = $v->user_headimgurl;

            $item['student_id'] = $v->student_id ?? 0;

            $result[] = $item;
            Return $result;
        });

        return $result;
    }

    /**
     * 写客户轨迹
     * @param $msg
     */
    public function writeTrackSmall($msg, $sid, $uid)
    {

        $user_info = db('user_integral')->where('userid', $uid)->find();

        $natural_id = $user_info['natural_id'];
        $counselor_id = $user_info['counselor_id'];


        $request = \think\Request::instance();

        $header = $request->header();
        $host = $header['host'];
        $client = $header['user-agent'];

        $url = $request->url();
        $method = $request->method();


        $user_IP = $request->header()['x-forwarded-for'];
        $area2 = \app\common\util\Util::get_ip_info($user_IP);


        $data['host'] = $host;
        $data['url'] = $url;
        $data['method'] = $method;

        $data['m'] = $request->module();
        $data['c'] = $request->controller();
        $data['a'] = $request->action();

        $data['sid'] = $sid;
        $data['pid'] = $counselor_id;
        $data['counselor_id'] = $counselor_id;
        $data['natural_id'] = $natural_id;
        $data['uid'] = $uid;
        $data['ip'] = $user_IP;
        $data['pubdate'] = date('Y-m-d H:i:s', time());
        $data['client'] = $client;
        if (isset($area2[2])) {
            $data['area'] = $area2[2];
        }
        if (isset($area2[3])) {
            $data['area1'] = $area2[3];
        }
        if (isset($area2[4])) {
            $data['area2'] = $area2[4];
        }
        $data['msg'] = $msg;
        $track = new Track();
        $track->save($data);

        //更新学员表轨迹更新时间
        db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('track_update_time', time());
    }

    public static function write($msg, $sid, $uid)
    {

        $user_info = db('user_integral')->where('userid', $uid)->find();

        $natural_id = $user_info['natural_id'];
        $counselor_id = $user_info['counselor_id'];


        $request = \think\Request::instance();

        $header = $request->header();
        $host = $header['host'];
        $client = $header['user-agent'];

        $url = $request->url();
        $method = $request->method();

        $user_IP = $request->header()['x-forwarded-for'];
        $area2 = \app\common\util\Util::get_ip_info($user_IP);

        $data['host'] = $host;
        $data['url'] = $url;
        $data['method'] = $method;


        $data['m'] = $request->module();
        $data['c'] = $request->controller();
        $data['a'] = $request->action();

        $data['sid'] = $sid;
        $data['pid'] = $counselor_id;
        $data['counselor_id'] = $counselor_id;
        $data['natural_id'] = $natural_id;
        $data['uid'] = $uid;
        $data['ip'] = $user_IP;
        $data['pubdate'] = date('Y-m-d H:i:s', time());
        $data['client'] = $client;
        if (isset($area2[2])) {
            $data['area'] = $area2[2];
        }
        if (isset($area2[3])) {
            $data['area1'] = $area2[3];
        }
        if (isset($area2[4])) {
            $data['area2'] = $area2[4];
        }
        $data['msg'] = $msg;
        $track = new Track();
        $track->save($data);

        //更新学员表轨迹更新时间
        db('students')->where(['sid' => $sid, 'uid' => $uid])->setField('track_update_time', time());
    }

    /**
     * 写客户轨迹
     * @param $msg
     */
    public function writeTrack($msg, $counselor_id = 0)
    {

        $request = \think\Request::instance();

        $header = $request->header();
        $host = $header['host'];
        $client = $header['user-agent'];

        $url = $request->url();
        $method = $request->method();


        $user_IP = $request->header()['x-forwarded-for'];
        $area2 = \app\common\util\Util::get_ip_info($user_IP);


        $data['host'] = $host;
        $data['url'] = $url;
        $data['method'] = $method;

        $data['m'] = $request->module();
        $data['c'] = $request->controller();
        $data['a'] = $request->action();
        $data['id'] = $request->param('id', 0);
        $data['natural_id'] = $request->param('natural_id', 0);
        $data['sid'] = $request->param('sid', 0);
        $data['pid'] = $request->param('pid', 0);
        $data['counselor_id'] = $counselor_id ?? $request->param('counselor_id', 0);

        $data['uid'] = $request->param('uid', 0);

        $baseHelper = new \app\common\helper\BaseHelper();
        $data['share_type'] = $baseHelper->getPlace();
        $data['ip'] = $user_IP;
        $data['pubdate'] = date('Y-m-d H:i:s', time());
        $data['client'] = $client;
        if (isset($area2[2])) {
            $data['area'] = $area2[2];
        }
        if (isset($area2[3])) {
            $data['area1'] = $area2[3];
        }
        if (isset($area2[4])) {
            $data['area2'] = $area2[4];
        }
        $data['msg'] = $msg;


        $track = new Track();
        $track->save($data);

        //更新学员表轨迹更新时间
        db('students')->where(['sid' => $request->param('sid'), 'uid' => $request->param('uid')])->setField('track_update_time', time());
    }


    /**
     * @param $sid
     * @param $uid
     * @return int|string
     * 获取某个用户轨迹数量
     */
    public function getTrackCountByOne($sid, $uid)
    {
        $count = Track::where(['sid' => $sid, 'uid' => $uid])->count();
        return $count;
    }
}